package io.gbznt.modules.buss.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.gbznt.modules.buss.entity.*;
import io.gbznt.modules.buss.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.gbznt.common.utils.PageUtils;
import io.gbznt.common.utils.R;
import io.gbznt.common.utils.ShiroUtils;
import io.gbznt.common.validator.ValidatorUtils;
import io.gbznt.common.validator.group.AddGroup;
import io.gbznt.modules.sys.entity.SysConfigEntity;
import io.gbznt.modules.sys.entity.SysDictEntity;
import io.gbznt.modules.sys.entity.SysUserEntity;
import io.gbznt.modules.sys.service.SysConfigService;
import io.gbznt.modules.sys.service.SysDictService;
import io.gbznt.modules.sys.service.SysUserService;

/**
 * 田块信息
 *
 * @author gbznt
 * @email http://www.gbznt.com/
 * @date 2019-04-20 15:48:34
 */
@RestController
@RequestMapping("buss/bussfarmlandinfo")
public class BussFarmlandInfoController {

	@Autowired
	private BussFarmlandInfoService bussFarmlandInfoService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private BussRtuInfoService bussRtuInfoService;
	@Autowired
	private BussRtuEquipmentService bussRtuEquipmentService;
	@Autowired
	private BussCameraInfoService bussCameraInfoService;
	@Autowired
	private SysDictService sysDictService;
	@Autowired
	private BussRtuRecordService bussRtuRecordService;
	@Autowired
	private SysConfigService sysConfigService;

	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("buss:bussfarmlandinfo:list")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = bussFarmlandInfoService.queryPage(params);

		return R.ok().put("page", page);
	}

	/**
	 * 田块列表（包括摄像头、设备信息）
	 */
	@RequestMapping("/infoList")
	public R infoList(@RequestParam Map<String, Object> params) {
		String deptId = (String) params.get("deptId");
		String farmlandId = (String) params.get("farmlandId");

		List<BussFarmlandInfoEntity> bussFarmlandInfoEntityList = bussFarmlandInfoService
				.list(new QueryWrapper<BussFarmlandInfoEntity>().eq(StringUtils.isNotEmpty(deptId), "dept_id", deptId)
						.eq(StringUtils.isNotEmpty(farmlandId), "id", farmlandId).orderByDesc("create_time"));

		for (BussFarmlandInfoEntity bussFarmlandInfoEntity : bussFarmlandInfoEntityList) {
			// 田块下的摄像头
			List<BussCameraInfoEntity> bussCameraInfoEntityList = bussCameraInfoService.list(
					new QueryWrapper<BussCameraInfoEntity>().eq("farmland_info_id", bussFarmlandInfoEntity.getId()));
			bussFarmlandInfoEntity.setBussCameraInfoEntityList(bussCameraInfoEntityList);

			// 田块下的RTU
			List<BussRtuInfoEntity> bussRtuInfoEntityList = bussRtuInfoService
					.list(new QueryWrapper<BussRtuInfoEntity>().eq("farmland_info_id", bussFarmlandInfoEntity.getId()));
			for (BussRtuInfoEntity bussRtuInfoEntity : bussRtuInfoEntityList) {
				// RTU下的设备
				List<BussRtuEquipmentEntity> bussRtuEquipmentEntityList = bussRtuEquipmentService
						.list(new QueryWrapper<BussRtuEquipmentEntity>().eq("rtu_id", bussRtuInfoEntity.getId()));
				bussRtuInfoEntity.setBussRtuEquipmentEntityList(bussRtuEquipmentEntityList);

			}
			bussFarmlandInfoEntity.setBussRtuInfoEntityList(bussRtuInfoEntityList);

		}

		return R.ok().put("list", bussFarmlandInfoEntityList);
	}

	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("buss:bussfarmlandinfo:info")
	public R info(@PathVariable("id") String id) {
		BussFarmlandInfoEntity bussFarmlandInfo = bussFarmlandInfoService.getById(id);

		SysUserEntity sysUserEntity = sysUserService.getById(bussFarmlandInfo.getHandler());
		if (null != sysUserEntity) {
			bussFarmlandInfo.setHandlerName(sysUserEntity.getName());
		}
		// 农作物
		SysDictEntity sysDictEntity = sysDictService.getById(bussFarmlandInfo.getCropDict());
		if (null != sysDictEntity) {
			bussFarmlandInfo.setCropDictName(sysDictEntity.getValue());
		}

		// 查询出最新且值不为空的上行报文
		List<BussRtuRecordEntity> sxbwList = bussRtuRecordService.getSxbw();
		// 用于判断该田块下是否有闸门信息
		int count = sxbwList.size();

		// 查询该田块下的摄像头信息
		QueryWrapper<BussCameraInfoEntity> sxtQw = new QueryWrapper<>();
		sxtQw.eq("farmland_info_id", id);
		List<BussCameraInfoEntity> sxtList = bussCameraInfoService.list(sxtQw);
		// 获取摄像头的token信息
		SysConfigEntity sce = sysConfigService.getById(1);
		Map<String, Object> map = new HashMap<>();
		if (sxtList.size() > 0) {
			map.put("token", sce.getRemark());// token
			map.put("source", sxtList.get(0).getSerialNum());// 序列号
		}

		return R.ok().put("bussFarmlandInfo", bussFarmlandInfo).put("sxbw", sxbwList.get(0)).put("count", count)
				.put("map", map);
	}

	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("buss:bussfarmlandinfo:save")
	public R save(@RequestBody BussFarmlandInfoEntity bussFarmlandInfo) {
		ValidatorUtils.validateEntity(bussFarmlandInfo, AddGroup.class);

		Integer namesNum = bussFarmlandInfoService
				.count(new QueryWrapper<BussFarmlandInfoEntity>().eq("name", bussFarmlandInfo.getName()));
		if (namesNum >= 1) {
			return R.error("该田块名称已存在");
		}

		bussFarmlandInfo.setCreateId(ShiroUtils.getUserId() + "");
		bussFarmlandInfo.setCreateName(ShiroUtils.getUserName());
		bussFarmlandInfo.setCreateTime(new Date());

		bussFarmlandInfoService.save(bussFarmlandInfo);

		return R.ok();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("buss:bussfarmlandinfo:update")
	public R update(@RequestBody BussFarmlandInfoEntity bussFarmlandInfo) {
		ValidatorUtils.validateEntity(bussFarmlandInfo, AddGroup.class);

		Integer namesNum = bussFarmlandInfoService.count(new QueryWrapper<BussFarmlandInfoEntity>()
				.eq("name", bussFarmlandInfo.getName()).ne("id", bussFarmlandInfo.getId()));
		if (namesNum >= 1) {
			return R.error("该田块名称已存在");
		}

		bussFarmlandInfoService.uodateByid(bussFarmlandInfo);// 全部更新

		return R.ok();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("buss:bussfarmlandinfo:delete")
	public R delete(@RequestBody String[] ids) {
		bussFarmlandInfoService.removeByIds(Arrays.asList(ids));

		return R.ok();
	}

}
